<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
</head>

<body>
    <!-- 文件的选择 -->
    <input type="file" id="file1">
    <!-- 上传文件的按钮 -->
    <button id="btn">上传文件</button>
    <br>
    <!-- 显示上传的图片 -->
    <img src="" id="img1" width="880px">
    <!-- 进度条 -->
    <div class="progress" style="width: 500px;margin:10px 0px;">
        <div class="progress-bar progress-bar-info progrss-bar-striped active" id="perent" style="width: 0%;">0%</div>
    </div>
</body>

</html>
<script src="./js/jquery.js"></script>
<script>
    // 获取上传文件的按钮
    const btn = document.querySelector('#btn');
    // 给按钮添加点击事件
    btn.addEventListener('click', function () {
        // 获取到选择的文件列表
        const files = document.querySelector('#file1').files;
        console.log(files.length)
        if (files.length > 0) {
            // 追加文件
            const fd = new FormData();
            fd.append('avatar', files[0]);
            // 发送请求
            const xhr = new XMLHttpRequest();
            // 监听上传进度
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    // e.loaded已经传输的字节
                    // e.total需要传输的总字节
                    const perent = Math.ceil((e.loaded / e.total) * 100)
                    $("#perent").attr('style', 'width:' + perent + '%').html(perent + "%")
                    if (perent == 100) {
                        $("#perent").attr('style', 'width:0%').html("0%")
                    }
                }
            }
            xhr.open('post', 'http://www.liulongbin.top:3006/api/upload/avatar')
            xhr.send(fd);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    console.log(fd.size)
                    const dt = JSON.parse(xhr.responseText).url;
                    console.log(dt);
                    document.querySelector('#img1').src = 'http://www.liulongbin.top:3006' + dt;
                }
            }
        } else {
            alert('上传失败')
        }
    })
</script>